package com.hsgene.common.util.qrcode;

import com.swetake.util.Qrcode;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.awt.*;
import java.awt.image.BufferedImage;

/**
 * 支付二维码
 *
 * @author wxf
 * @date 2018/8/28 9:46
 **/
public class PayQrCodeUtils {

    /**
     * Log
     */
    private static Logger LOGGER = LogManager.getLogger(PayQrCodeUtils.class);

    /**
     * 生成二维码
     *
     * @param url 地址
     * @return
     */
    public static BufferedImage qrCodeEncode(String url) {
        BufferedImage bufferedImage = null;
        try {
            Qrcode qrcode = new Qrcode();
            // 纠错级别（L 7%、M 15%、Q 25%、H 30%）和版本有关
            qrcode.setQrcodeErrorCorrect('M');
            qrcode.setQrcodeEncodeMode('B');
            qrcode.setQrcodeVersion(7);
            //大小一般为版本号-1
            int imageSize = 67 + 12 * (7 - 1);
            //设置偏移量
            int pixoff = 2;
            byte[] b = url.getBytes("GBK");
            bufferedImage = new BufferedImage(imageSize, imageSize, BufferedImage.TYPE_INT_RGB);
            //创建图层
            Graphics2D g2d = bufferedImage.createGraphics();
            g2d.setBackground(Color.WHITE);
            //矩形 X、Y、width、height
            g2d.clearRect(0, 0, imageSize, imageSize);
            g2d.setColor(Color.BLACK);
            if (0 < b.length && b.length < 123) {
                boolean[][] s = qrcode.calQrcode(b);
                for (int i = 0; i < s.length; i++) {
                    for (int j = 0; j < s.length; j++) {
                        if (s[j][i]) {
                            //根据QRcode规则填充黑白点
                            g2d.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);
                        }
                    }
                }
            }
            //释放资源
            g2d.dispose();
            //刷新此bufferedImage正在使用的所有可重构的资源
            bufferedImage.flush();
        } catch (Exception e) {
            LOGGER.error("make qr coder is error...", e);
        }
        return bufferedImage;
    }

}
